<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\admin;

use app\mill\builder\Admin;
use app\mill\builder\ZBuilder;
use app\user\model\UserGroup as UserGroupModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Give as GiveModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Stat as StatModel;
use app\user\model\User as UserModel;
use app\mill\model\Client as ClientModel;
use app\admin\model\Config as ConfigModel;
use think\Db;

/**
 * 生产管理控制器
 * @package app\admin\controller
 */
class Give extends Admin
{
    //初始化
    protected function initialize(){
        parent::initialize();
        GiveModel::init();
    }
    //首页
    public function index(){

        $order_id = input('order_ids');
        if (strpos($order_id, ',') !== false)$this->error('暂不支持批量查看');
        session('_archives_order_id',$order_id);

        //获取生产状态字段
        $give_status = GiveModel::$give_status_search;
        unset($give_status[0]);

        $url = url('mill/stat/ajaxSpeedShow');
        $top_html = StatModel::giveHtml($url,ClientModel::getMillList(),$give_status);

        //获取菜单列表
        $menu = StatModel::getMenu('mill',365);
        if(!empty($menu[0]['child'])){
            $child[] = $menu[0]['child'][0];

            foreach ($give_status as $gk=>$gs){
                $v = $menu[0]['child'][1];
                $v['title'] = $gs.$v['title'];
                $v['url_value'] = $v['url_value'].(strpos($v['url_value'],'?') === false ? '?':'&')."status={$gk}";
                $v['extra_class'] = 'fixed_give_sort';
                $v['extra_attr'] = 'data-status="'.$gk.'"';

                $child[] = $v;
            }
            $menu[0]['child'] = $child;
        }
        //额外HTML代码
        $extra_html = StatModel::fixedHtml($menu);

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('') // 页面标题
            ->setTableName('mill_order_archives') // 设置表名
            ->setExtraHtml($top_html,'block_top')
            ->setExtraHtml($extra_html)
            ->fetch(); // 渲染模板
    }
    //工程列表
    public function orderList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,s.staff as sales,c.company')
            ->leftJoin('mill_client c','o.client_id=c.id')
            ->leftJoin('mill_staff s','o.sales_id=s.id')
            ->where($map)
            ->group('o.id')
            ->order('o.id desc')
            ->paginate()
            ->each(function ($v){

                $archives = Db::name('mill_order_archives')->field('sum(number) as number_sum,sum(row_area) as area_sum')->where(['order_id'=>$v['id']])->find();

                $archives['area_sum'] = round($archives['area_sum'],6);

                $v = array_merge($v,$archives);

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('批次列表('.$data_list->total().')') // 页面标题
            ->setTableName('mill_order') // 设置表名
            //->hideCheckbox()
            ->setSearch(['o.engineering' => '工程名称', 'o.archives_sn' => '档案号', 'c.company' => '客户名称', 'o.back' => '内勤']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['archives_sn', '档案号','jump_right','','order_id=__id__','badge-green',['group'=>'批次信息']],
                ['engineering', '工程名称','','','','',['group'=>'批次信息']],
                ['number_sum', '数量(件)','','','','',['group'=>'批次信息']],
                ['area_sum', '面积(㎡)','','','','',['group'=>'批次信息']],
            ])
            ->addTopButton('batchIsLock',['title' => '批次冻结','href'=>url('mill/order/batchIsLock'),'class'=>'btn btn-danger ajax-post confirm'],false)
            ->setRowList($data_list) // 设置表格数据
            ->setWidth('25%') // 设置表格宽度
            ->setColumnWidth([
                'id'  => 60,
                'archives_sn'  => 120,
                'number_sum'  => 40,
            ])
            ->fetch(); // 渲染模板
    }
    //所有产品
    public function archives()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $order_id = input('order_id',session('_archives_order_id'));
        // 获取查询条件
        $map = $this->getMap();

        if(empty($map) && $order_id)$map[] = ['a.order_id','=',$order_id];

        // 数据列表
        $data_list = [];
        $total = '';

        if(!empty($map)){
            $data_list = Db::name('mill_order_archives')
                ->alias('a')
                ->where($map)
                ->order('a.order_id desc,a.id asc')
                ->select();

            if(!empty($data_list)){
                foreach ($data_list as &$v){
                    $v['id_btn'] = '<button class="layui-btn layui-btn-xs layui-btn-green">展开查询</button>';
                }

                $order_id = $data_list[0]['order_id'];
                $total = "(".count($data_list).")";
            }
        }

        $title = "产品列表{$total}";

        //获取生产状态字段
        $give_sort = GiveModel::$give_status_search;
        unset($give_sort[0]);
        $give_sort = array_keys($give_sort);

        if($order_id){
            $order = Db::name('mill_order')->where(['id'=>$order_id])->find();
            if(!empty($order)){
                $title = "{$order['engineering']} {$order['batch']}({$order['archives_sn']}) {$title}";

                $give_sort = explode(',',$order['give_sort']);

            }
        }

        //JS
        $js = '<script type="text/javascript">
                layui_func["id_btn"] = function (){
                    $(".fixedName").click(function(){
                        var give_sort = '.json_encode($give_sort).';
                        
                        //隐藏所有工艺环节，并取消底部列表的左侧选中
                        $(".fixed_give_sort").hide();
                        $(".fixed .list .item").removeClass("on");
                        $(".fixed_give_sort").removeClass("item");
                        //只显示该工程已有的工艺环节
                        $.each($(".fixed_give_sort"),function(i,v){
                            var status = $(v).attr("data-status");
                            if($.inArray(status,give_sort) >= 0){
                                $(v).show();
                                $(".fixed_give_sort").addClass("item");
                            }
                        });
                        //默认选中底部列表的左侧第一个
                        $(".fixed .list .item").eq(0).addClass("on");
                    })
                };
            </script>';

        $addTopButton = [
            'batchIsLock'           =>  [['title' => '冻结产品','href'=>url('mill/order/batchIsLock',['ids'=>$order_id]),'class'=>'btn btn-danger ajax-get confirm'],false],
            'batchEnIsLock'         =>  [['title' => '解除冻结','href'=>url('mill/order/batchEnIsLock',['ids'=>$order_id]),'class'=>'btn btn-default ajax-get confirm'],false],
            'able'                  =>  [['title' => '修改生产状态','href'=>url('mill/give/able',['order_id'=>$order_id]),'class'=>'btn btn-default dch-js-get']],
            'ableGive'              =>  [['title' => '加入发货单','href'=>url('mill/order/ableGive',['order_id'=>$order_id]),'class'=>'btn btn-default js-get','target-form'=>'archives_ids']],
            'archivesPrint'         =>  [['title' => '标签打印','href'=>url('mill/give/archivesPrint',['order_id'=>$order_id]),'class'=>'btn btn-default dch-js-get','target-form'=>'archives_id','float'=>'right'],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']]],
            'archivesPrint2'        =>  [['title' => '标签打印LOGO','href'=>url('mill/give/archivesPrint',['order_id'=>$order_id,'watermark'=>1]),'class'=>'btn btn-default dch-js-get','target-form'=>'archives_id','float'=>'right'],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']]],
            'print'                 =>  [['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print','float'=>'right','lay-event'=>'quality-print']],
        ];
        if(empty($order_id))$addTopButton = [];

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order_archives') // 设置表名
            //->hideCheckbox()
            ->setSearchArea([
                ['select:5', 'a.order_id', '档案号/工程名称','','',OrderModel::getList("concat(archives_sn,' ',engineering) as str_name"),$order_id],
            ])
            ->addColumns([ // 批量添加列
                //['color', '颜色','','','','',['group'=>'颜色','group_class'=>'badge-warning']],
                ['sort', '序号','','','','badge-warning',['group'=>'产品信息']],
                ['color', '颜色','','','','',['group'=>'产品信息']],
                ['page', '图纸页码','','','','',['group'=>'产品信息']],
                ['cutting', '开料(L)','','','','',['group'=>'产品信息']],
                ['size', '开料(H)','','','','',['group'=>'产品信息']],
                ['long', 'L(mm)','','','','',['group'=>'产品信息']],
                ['high', 'H(mm)','','','','',['group'=>'产品信息']],
                ['thickness', '板厚(mm)','','','','',['group'=>'产品信息']],
                ['model', '板型','','','','',['group'=>'产品信息']],
                ['model_sn', '铝板编号','','','','',['group'=>'产品信息']],
                ['one_area', '单件面积(m²)','','','','',['group'=>'产品信息']],
                ['row_area', '合计面积(m²)','','','','',['group'=>'产品信息']],
                ['number', '数量','','','','',['group'=>'产品信息']],
                ['id_btn', '操作','jump_bottom','','order_id=__order_id__&archives_id=__id__','',['group'=>'操作']],
            ])
            ->setExtraJs($js)
            ->addTopButtons($addTopButton)
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 50,
                'sort'  => 60,
                'archives_sn'  => 120,
                'number'  => 50,
                'cutting'  => 50,
                'size'  => 50,
                'long'  => 50,
                'high'  => 50,
                'thickness'  => 50,
                'id_btn'  => 70,
                'one_area'  => 90,
                'row_area'  => 110,
                'page'  => 110,
            ])
            ->fetch(); // 渲染模板
    }
    public function archivesGive()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $status = '';
        $quality_repair = '';
        $sort_between = [];
        $map = $this->getMap();
        $map2 = '';
        if(!empty($map)){
            foreach ($map as $k=>$v){
                if(in_array('a_sort',$v)){
                    $a_sort = explode('-',$v[2]);
                    $sort = !empty($a_sort[0])?$a_sort[0]:'';
                    $counter = !empty($a_sort[1])?$a_sort[1]:'';
                    unset($map[$k]);
                }
                elseif(in_array('g.status',$v)){
                    $status = $v[2];
                }
                elseif(in_array('a_sort1',$v)){
                    $sort_between[0] = $v[2];
                    unset($map[$k]);
                }
                elseif(in_array('a_sort2',$v)){
                    $sort_between[1] = $v[2];
                    unset($map[$k]);
                }
                elseif(in_array('g.quality_repair',$v)){
                    $quality_repair = $v[2];
                }
            }
        }
        // 获取查询条件
        $id = input('id');
        $map[] = ['g.order_id','=',$id];
        if(is_numeric($status)){
            $map[] = ['g.quality_status','>=',0];
        }
        $archives_id = input('archives_id');
        if($archives_id)$map[] = ['g.archives_id','=',$archives_id];
        if(!empty($sort))$map[] = ['a.sort','=',$sort];
        if(!empty($counter))$map[] = ['g.counter','=',$counter];

        $str_int = 999999;
        if(count($sort_between) == 2){
            $sort_between2 = [];
            if(strpos($sort_between[0],'-') && strpos($sort_between[1],'-')){
                $sort_between2[0] = explode('-',$sort_between[0])[1];
                $sort_between2[1] = explode('-',$sort_between[1])[1];

                $sort_between[0] = explode('-',$sort_between[0])[0];
                $sort_between[1] = explode('-',$sort_between[1])[0];
            }
            if(strpos($sort_between[0],'#') || strpos($sort_between[1],'#')){
                $sort_between[0] = str_replace('#',$str_int,$sort_between[0]);
                $sort_between[1] = str_replace('#',$str_int,$sort_between[1]);
            }
            $map2 .= " CONVERT (REPLACE(a.sort,'#','{$str_int}'),signed) BETWEEN {$sort_between[0]} AND {$sort_between[1]} ";
            if(!empty($sort_between2))$map2 .= " and g.counter BETWEEN {$sort_between2[0]} AND {$sort_between2[1]} ";
        }
        sort($map);

        //更新产品明细
        ArchivesModel::checkGive($id,$archives_id);

        $archvices = ArchivesModel::getOneStat($id);

        $archvices_str = "产品总量：{$archvices['number_sum']}&nbsp;&nbsp;&nbsp;&nbsp;总面积：{$archvices['area_sum']}&nbsp;&nbsp;&nbsp;&nbsp;已完成面积：{$archvices['area_ok_sum']}&nbsp;&nbsp;&nbsp;&nbsp;未完成面积：{$archvices['area_on_sum']}&nbsp;&nbsp;&nbsp;&nbsp;开料：{$archvices['status1']}&nbsp;&nbsp;&nbsp;&nbsp;打磨：{$archvices['status2']}&nbsp;&nbsp;&nbsp;&nbsp;焊接：{$archvices['status3']}&nbsp;&nbsp;&nbsp;&nbsp;组装：{$archvices['status4']}&nbsp;&nbsp;&nbsp;&nbsp;喷涂：{$archvices['status5']}&nbsp;&nbsp;&nbsp;&nbsp;发货：{$archvices['status6']}";

        // 数据列表
        $_listRows = input('list_rows',GiveModel::$_listRows);
        $data_list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field('g.*,g.give_sn as give_sn_img,a.model,a.thickness,a.one_area,a.color,a.sort as a_sort,a.page,a.model_sn,a.cutting,a.size,a.long,a.high,a.plank')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where($map)
            ->where($map2)
            ->orderRaw("CONVERT (REPLACE(a.sort,'#','{$str_int}'),signed) asc,g.id asc")
            ->select();
        //->paginate($_listRows);

        //工程信息
        $order = Db::name('mill_order')->where(['id'=>$id])->find();

        //JS
        $js = '
        <script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/jsbarcode.all.min.js?v=20180327"></script>
        <script type="text/javascript">
            $(function(){
                $(".barcode").each(function(i){
                    var val = $(this).data("val");
                    $(this).JsBarcode(val,{displayValue:false});
                });
            })
        </script>
        ';
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle("{$order['engineering']} {$order['archives_sn']} 产品明细") // 页面标题
            ->setTableName('mill_order_archives_give') // 设置表名
            //->hideCheckbox()
            ->setPageTips($archvices_str)
            ->setSearchArea([
                ['select:2', 'g.quality_repair', '打印状态', 'eq','',GiveModel::$quality_repair],
                ['select:2', 'g.status', '产品状态', 'eq','',GiveModel::$give_status_search],
                ['text:1', 'a_sort', '序号查询'],
                ['text:1', 'a_sort1', '序号范围查询1'],
                ['text:1', 'a_sort2', '序号范围查询2'],
            ])
            ->addColumns([ // 批量添加列
                ['sort', '序号'],
                ['model_sn', '编号'],
                ['long', '长(L)'],
                ['high', '宽(W)'],
                ['one_area', '单件面积M²'],
                ['color', '颜色'],
                ['plank', '板材'],
                ['thickness', '板厚MM'],
                ['model', '板型'],
                ['a_sort','序号','callback',function($value, $data){
                    $value = "{$value}-{$data['counter']}";
                    return $value;
                },'__data__'],
                ['give_sn','产品条形码编号','callback',function($value, $data){
                    if($data['quality_old_id']>0)$value .= '<a>(补)</a>';
                    return $value;
                },'__data__'],
                ['status','产品状态','callback',function($value, $data){
                    $str = '';

                    if($data['address_status']<0)$str = '<span class="label label-warning">已锁定</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                    //质检
                    if($data['quality_status']<0)$uid = $data['quality_uid'];
                    //生产
                    else $uid = GiveModel::giveStatusOrUid($data['status_flow'],'',$value);
                    //部门信息
                    if($uid){
                        $user = Db::name('admin_user')
                            ->alias('u')
                            ->field('u.nickname,g.name as group_name')
                            ->leftJoin('admin_user_group g','g.id=u.group')
                            ->where(['u.id'=>$uid])
                            ->find();
                        if($user)$str .= "{$user['group_name']}[{$user['nickname']}]：";
                    }

                    $str .= '<span class="label label-primary">'.GiveModel::$give_status[abs($value)];
                    if($data['quality_status']<0)$str .= GiveModel::$quality_status[$data['quality_status']];
                    $str .= '</span>';

                    return $str;
                },'__data__'],
                ['quality_repair','打印状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,GiveModel::$quality_repair[$value]);
                    return $status;
                },'__data__'],
                ['give_sn_img','产品条形码','callback',function($value, $data){
                    //$value = '<div class="js-gallery"> <img class="image" data-original="'.plugin_url('Barcode/Barcode/generate', ['text' => $value]).'" src="'.plugin_url('Barcode/Barcode/generate', ['text' => $value]).'"></div>';
                    $value = '<div class="js-gallery"> <img class="image barcode" data-val="'.$value.'" data-original="" src=""></div>';
                    return $value;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('able',['title' => '更新状态','href' => url('able',['order_id' => $id]),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['780px', '90%'], 'title' => ['批量更新产品状态', 'font-size:24px;text-align: center;']])
            ->addTopButton('addressDisable',['title' => '批量锁定','href' => url('addressDisable',['address_status' => -1]),'icon'=>'','class'=>'btn btn-primary ajax-post confirm'])
            ->addTopButton('addressDisable',['title' => '批量解锁','href' => url('addressDisable',['address_status' => 0]),'icon'=>'','class'=>'btn btn-primary ajax-post confirm'])
            ->addTopButton('archivesPrint',['title' => '批量打印(不带LOGO)','href' => url('archivesPrint',['order_id' => $id,'archives_id'=>$archives_id,'status'=>$status,'quality_repair'=>$quality_repair,'page'=>input('page',1),'list_rows'=>$_listRows]),'icon'=>'','class'=>'btn btn-primary dch-js-get'],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->addTopButton('archivesPrint',['title' => '批量打印(带LOGO)','href' => url('archivesPrint',['order_id' => $id,'archives_id'=>$archives_id,'status'=>$status,'quality_repair'=>$quality_repair,'watermark'=>1,'page'=>input('page',1),'list_rows'=>$_listRows]),'icon'=>'','class'=>'btn btn-primary dch-js-get'],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->addRightButton('archivesPrint',['title' => '打印(不带LOGO)','href' => url('archivesPrint',['id' => '__id__','page'=>1]),'class'=>'btn btn-default disable-dch','icon'=>''],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->addRightButton('archivesPrint',['title' => '打印(带LOGO)','href' => url('archivesPrint',['id' => '__id__','watermark'=>1,'page'=>1]),'class'=>'btn btn-default disable-dch','icon'=>''],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->setColumnWidth([
                'sort'    =>  50,
                'page'    =>  65,
                'cutting'    =>  50,
                'size'    =>  50,
                'one_area'    =>  80,
                'long'    =>  52,
                'high'    =>  52,
                'color'    =>  120,
                'thickness'    =>  60,
                'a_sort'    =>  60,
                'give_sn'    =>  130,
                'status'    =>  150
            ])// 设置列宽
            ->setExtraJs($js)
            ->setRowList($data_list) // 设置表格数据
            //->noPages()
            ->fetch(); // 渲染模板
    }
    //打印条形码
    public function archivesPrint(){

        //打印单个条形码
        $id = input('id');
        //批量打印条形码
        $ids = input('ids');
        $status = input('status');
        $order_id = input('order_id');
        $archives_id = input('archives_id');
        //批量打印补件条形码
        $quality_repair = input('quality_repair');
        //根据原件ID查补件
        $quality_old_id = input('quality_old_id');
        //是否打印水印
        $watermark = input('watermark')?"<img style='width:130px;' src='".config('template.tpl_replace_string')['__ADMIN_IMG__']."/logo-signin.png'>":'';
        //$watermark = '';
        //是否更新打印状态
        $is_quality_repair = true;
        if($quality_repair == 1 || $quality_old_id)$is_quality_repair = true;

        $where = [['g.id','=',$id]];
        if(!empty($ids))$where = [['g.id','in',$ids]];
        elseif($order_id)$where = [['g.order_id','=',$order_id]];
        elseif($quality_old_id){
            $quality_old_str = explode('_',$quality_old_id);
            if(empty($quality_old_str[1]))$quality_old_str[1] = 'eq';
            $where = [['g.quality_old_id',$quality_old_str[1],$quality_old_str[0]]];
        }
        //elseif ($quality_repair)$where = [['g.quality_repair','=',$quality_repair]];

        if($archives_id)$where = [['g.archives_id','in',$archives_id]];
        if(is_numeric($status)){
            $where[] = ['g.status','=',$status];
            $where[] = ['g.quality_status','>=',0];
        }
        if(is_numeric($quality_repair)){
            $where[] = ['g.quality_repair','=',$quality_repair];
        }
        $where[] = ['g.quality_status','>',-3];

        //更新产品明细
        ArchivesModel::checkGive($order_id);

        $give_id = '';
        $list_rows = input('list_rows',GiveModel::$_listRows);
        $page = input('page',1);
        if(!empty($id) || !empty($ids))$page = 1;
        $_listRows['list_rows'] = $list_rows;
        $_listRows['page'] = $page;
        $list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->field('a.*,o.batch,g.give_sn,g.counter,g.quality_old_id,g.id as give_id,g.sort as give_sort')
            ->where($where)
            //->orderRaw('convert(a.sort,signed),g.sort asc')
            ->order('g.id asc')
            ->select();
        //->paginate($_listRows);

        $html = '<html><head></head><body style="margin: 0;margin-left: 3px;">';

        if(!empty($list[0])){
            $order = Db::name('mill_order')->where(['id'=>$list[0]['order_id']])->find();
            $i = count($list);
            foreach ($list as $k=>$v){

                $give_id .= ",{$v['give_id']}";

                $qrcode = '<div style="width: 50px;height: 50px;margin: 0 3px;" class="qrcode qrcode_copy" data-val="'.$v['give_sn'].'"></div>';
                $qrcode_copy = '<div style="width: 50px;height: 50px;margin: 0 3px;" class="qrcode_copy" data-val="'.$v['give_sn'].'"></div>';
                //是否补件
                if($v['quality_old_id']>0)$v['give_sn'] .= '(补件)';
//批<br>次 $v['batch']
                $margin = 'margin-bottom: 35px;';
                $width = '98mm';
                $height = '78mm';
                if($i == $k+1)$margin = '';
                //颜色字号大小
                $color_size = 20;
                if(mb_strlen($v['color']) > 16)$color_size = 14;

                $html .= '<table border="1" style="font-size: 12px;text-align: center;border-collapse: collapse;word-break: break-all;width: '.$width.';height: '.$height.';'.$margin.'">
<tbody style="border: solid 1px black;">

<tr style="height: 20px">
<td colspan="1" style="width: 50px;height: 50px;">'.$qrcode.'</td>
<td colspan="4" style="font-size: 16px;text-align: center;"><div style="font-size: 16px;text-align: center;line-height: 18px;font-weight: 900;">'.$order['engineering'].'</div></td>
<td colspan="1" style="width: 50px;height: 50px;">'.$qrcode_copy.'</td>
</tr>

<tr style="height: 20px">
<td colspan="1" style="font-size: 16px;text-align: center;font-weight: 900;"><div style="">档案号</div></td>
<td colspan="4" style="font-size: 16px;text-align: center;"><div style="">'.$order['archives_sn'].'('.$order['batch'].')</div></td>
<td colspan="1" rowspan="5" style="writing-mode: vertical-rl;transform: rotate(360deg);"><div style="font-size: 16px;font-weight: 900;">'.$v['give_sn'].'</div></td>
</tr>

<tr style="height: 20px">
<td colspan="1" rowspan="4" style="writing-mode: vertical-rl;transform: rotate(180deg);"><div style="font-size: 16px;font-weight: 900;">'.$v['give_sn'].'</div></td>
<td colspan="1" rowspan="2" style="width: 34px;font-size: 16px;text-align: center;font-weight: 900;"><div style="">序号</div></td>
<td colspan="1" rowspan="2" style="font-size: 16px;text-align: center;"><div style="">'.$v['sort'].'-'.$v['counter'].'</div></td>
<td colspan="1" style="font-size: 16px;text-align: center;font-weight: 900;"><div style="">数量</div></td>
<td colspan="1" style="font-size: 16px;text-align: center;"><div style="">'.$v['counter'].'/'.$v['number'].'</div></td>
</tr>

<tr style="height: 20px">
<td colspan="1" style="font-size: 16px;text-align: center;font-weight: 900;"><div style="">图号</div></td>
<td colspan="1" style="font-size: 16px;text-align: center;"><div style="">'.$v['page'].'</div></td>
</tr>

<tr style="height: 20px">
<td colspan="1" style="width: 34px;font-size: 16px;text-align: center;font-weight: 900;"><div style="">颜色</div></td>
<td colspan="3" style="font-size: 16px;text-align: center;"><div style="">'.$v['color'].'</div></td>
</tr>

<tr style="height: 20px">
<td colspan="1" style="width: 34px;font-size: 16px;text-align: center;font-weight: 900;"><div style="">铝板编号</div></td>
<td colspan="2" style="font-size: 16px;text-align: center;"><div style="">'.$v['model_sn'].'</div></td>
<td colspan="1" style="font-size: 16px;text-align: center;"><div style="">'.$v['long'].' * '.$v['high'].'</div></td>
</tr>

<tr style="height: 20px">
<td colspan="1" style="width: 50px;height: 50px;">'.$qrcode_copy.'</td>
<td colspan="4" style="font-size: 16px;text-align: center;"><div style="font-size: 23px;text-align: center;line-height: 18px;font-weight: 900;">'.$watermark.'</div></td>
<td colspan="1" style="width: 50px;height: 50px;">'.$qrcode_copy.'</td>
</tr>

</tbody>
</table>';
            }
        }
        if($html){
            $html .= '<script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/core/jquery.min.js?v=20180327"></script><script src="'.config('template.tpl_replace_string')['__HOME_JS__'].'/jquery.qrcode.min.js?v=20180327"></script><script type="text/javascript">
                $(function(){
                
                    $(".qrcode").each(function(i){
                        var val = $(this).data("val");
                        //$(this).qrcode({
                        //    text: val,
                        //    width: 50,
                        //    height: 50
                        //});
                        $(".qrcode_copy[data-val="+val+"]").qrcode({
                            text: val,
                            width: 50,
                            height: 50
                        });
                        
                    });
                    //调用打印功能
                    window.print();
                    
                });
            </script>';
        }

        $html .= '</body></html>';

        //默认已在打印中,更新打印状态
        $give_id = trim($give_id,',');
        if($is_quality_repair && $give_id){
            Db::name('mill_order_archives_give')
                ->where([['id','in',$give_id]])
                ->update(['quality_repair'=>2]);
        }
        //更新打印时间
        if(!empty($order) && empty($order['print_time']))Db::name('mill_order_archives_give')->where(['id'=>$order])->update(['print_time'=>time()]);

        echo $html;exit;

    }
    //更新产品状态
    public function able(){

        //工程ID
        $order_id = input('order_id');
        //获取发货部的产品状态
        $address_status = GiveModel::$last_give_status;

        if ($this->request->isPost()){

            $role_status = input('status');
            if(!is_numeric($role_status))$this->error('请选择产品状态');

            //如果order_ids存在，则默认为批量清空扫码状态
            $order_ids = input('order_ids');
            if(!empty($order_ids)){
                $order_ids = is_array($order_ids)?implode(',',$order_ids):$order_ids;
                $where = [['id','in',$order_ids]];
                $update = [
                    'give_pro'          =>  0,
                    'give_status'       =>  0,
                    'address_price'     =>  0,
                    'address_area'      =>  0,
                    'address_number'    =>  0,
                ];
                Db::name('mill_order')->where($where)->update($update);

                $where = [['order_id','in',$order_ids]];
                Db::name('mill_order_archives')->where($where)->update(['status'=>0,]);

                $update = [
                    'status'=>0,
                    'status_flow'=>'',
                    'car_id'=>'',
                    'address_sn'=>'',
                    'address_date'=>'',
                    'address_time'=>'',
                    'address_status'=>'',
                    'quality_status'=>0,
                    'quality_note'=>'',
                    'quality_flow_group'=>'',
                    'quality_uid'=>'',
                ];

                Db::name('mill_order_archives_give')->where($where)->update($update);
                Db::name('mill_order_archives_give_log')->where($where)->delete();
                Db::name('mill_order_archives_address_price')->where($where)->delete();
            }
            else{

                $give_search = input('give_search');
                $give_search2 = input('give_search2');
                if(empty($give_search2))$give_search2 = $give_search;

                if(empty($give_search))$this->error('请输入起始序号');
                if($give_search<0)$this->error('输入正常的起始序号');
                if($give_search2<0)$this->error('输入正常的截止序号');
                if($give_search>$give_search2)$this->error('输入正常的序号');
                if(count(explode('-',$give_search))>1)$this->error('起始序号格式不支持');
                if(count(explode('-',$give_search2))>1)$this->error('截止序号格式不支持');

                $order = Db::name('mill_order')
                    ->alias('o')
                    ->field('o.*,c.is_lock,o.status as order_status,o.is_lock as is_lock2')
                    ->leftJoin('mill_client c','c.id=o.client_id')
                    ->where(['id'=>$order_id])
                    ->find();

                //验证该产品是否已冻结
                if($order['is_lock'] == 0 || $order['is_lock2'] == 0)$this->error('该工程已冻结，请联系管理员');
                //验证该产品是否已取消生产
                if($order['quality_status'] == -3)$this->error('该产品已取消生产');
                //验证该产品是否已取消生产工艺
                if(empty($order['give_sort']))$this->error('该工程未选择生产工艺');
                //验证该产品是否有此生产工艺
                if(!in_array($role_status,explode(',',$order['give_sort'])))$this->error('该工程暂无此工艺');

                //循环处理
                for ($i=$give_search,$j=$give_search2;$i<=$j;$i++){

                    $where = [
                        ['a.sort','=',$i],
                        ['g.order_id','=',$order_id],
                        ['g.status','>=',0],
                        //['g.status','<',$role_status],
                    ];

                    $give = Db::name('mill_order_archives_give')
                        ->alias('g')
                        ->field('g.*,o.is_process')
                        ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                        ->leftJoin('mill_order o','o.id=g.order_id')
                        ->where($where)
                        ->group('g.id')
                        ->select();

                    $archives_id = '';
                    foreach ($give as $gv){

                        //补上各流水线状态，默认当前操作部门用户
                        //$user = session('user_auth');
                        //$user['uid'] = UID;
                        //$user['mill_id'] = Db::name('admin_user')->where(['id'=>UID])->value('mill_id');
                        $user['uid'] = '';
                        $user['mill_id'] = $order['mill_id'];
                        $user['group_id'] = '';
                        $sup_status = $role_status;//需要补充到的状态
                        $save = GiveModel::giveToStatus($user,$sup_status,$gv);
                        $log_list = isset($save['log_list'])?$save['log_list']:'';

                        $give_where = ['id'=>$give['id']];
                        if(Db::name('mill_order_archives_give')->where($give_where)->update($save)){
                            //生成扫码记录
                            GiveModel::addGiveLog($log_list);
                            //检查更新产品主体状态
                            ArchivesModel::checkStatus($give,$give['give_sort']);
                        }

                        //$archives_id = $gv['archives_id'];
                    }
                    //ArchivesModel::checkStatus($archives_id,$role_status);

                }
            }

            //关闭子窗口，并刷新父窗口
            $this->success('操作成功','','_parent_reload');
        }

        $order = Db::name('mill_order')->where(['id'=>$order_id])->find();

        $order_give_sort = explode(',',$order['give_sort']);
        $give_sort = GiveModel::$give_status_search;
        foreach($give_sort as $gk=>$gv){
            if($gk > 0 && !in_array($gk,$order_give_sort))unset($give_sort[$gk]);
        }

        return ZBuilder::make('form')
            ->setPageTitle('更新产品状态') // 页面标题
            ->addStatic('archives_sn', '档案编号', '', $order['archives_sn'])
            ->addFormItems([ // 批量添加表单项
                //['text:||||must', 'address_sn','发货单号', $address_sn],
                ['radio:12||||must', 'status', '产品状态','',$give_sort],
                ['text:6||||must', 'give_search', '序号范围','开始，例：1'],
                ['text:6||||must', 'give_search2', '序号范围','截止，例：999'],
            ])
            ->submitConfirm()
            ->layout(['archives_sn'=>12])
            ->fetch();

    }
    //产品首页统计
    public function giveIndexHtml($url = ''){
        $option = "{
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        legend: {
            
                        },
                        grid: {
                            left: '50',
                            right: '10',
                            bottom: '20',
                            top: '15',
                        },
                        xAxis: {
                            type: 'category',
                            data: data.head
                        },
                        yAxis: {
                            type: 'value'
                        },
                        series: data.series
                    }";

        $top_html = StatModel::topStatHtml($url,$option,['year','charts','rank']);

        return $top_html;
    }
    //产品首页
    public function giveIndex(){

        $order_id = input('order_ids');
        if (strpos($order_id, ',') !== false)$this->error('暂不支持批量查看');
        session('_archives_order_id',$order_id);

        $top_html = $this->giveIndexHtml(url('mill/stat/ajaxMonthGive'));

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('') // 页面标题
            ->setTableName('mill_order_archives') // 设置表名
            ->setExtraHtml($top_html,'block_top')
            ->fetch(); // 渲染模板
    }
    //工艺列表
    public function giveGroupList(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        //工艺选择
        $give_status = GiveModel::$give_status_search;
        unset($give_status[0]);

        // 获取查询条件
        $map = $this->getMap();
        // 数据列表
        $data_list = Db::name('mill_order_archives_give_log')
            ->alias('l')
            ->field('l.status,count(l.id) as number_sum,sum(l.one_area) as area_sum')
            ->where($map)
            ->group('l.status')
            ->order('l.status asc')
            ->select();
        if(!empty($data_list)){
            foreach ($data_list as &$v){
                $v['give_title'] = Db::name('admin_user_group')->where(['give_sort'=>$v['status']])->value('give_title');
                $v['busao'] = Db::name('mill_order_archives_give_log')->where(['status'=>$v['status'],'is_bu'=>1])->count();
            }
        }

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('工艺列表') // 页面标题
            ->setTableName('mill_order_archives_give_log') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['select:2', 'l.mill_id', '车间','','',ClientModel::getMillList()],
                ['select:2', 'l.status', '工艺环节','','',$give_status],
                ['daterange:2', 'l.status_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['give_title', '工艺环节','jump_right','','status=__status__','badge-green',['group'=>'工艺环节产量数据']],
                ['number_sum', '数量(件)','','','','',['group'=>'工艺环节产量数据']],
                ['area_sum', '面积(㎡)','','','','',['group'=>'工艺环节产量数据']],
                ['busao', '补扫数量(件)','','','','',['group'=>'工艺环节产量数据']],
            ])
            ->addTopButton('print',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print','float'=>'right','lay-event'=>'quality-print'])
            ->setRowList($data_list) // 设置表格数据
            ->setWidth('35%') // 设置表格宽度
            ->setColumnWidth([
                'id'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    //操作员列表
    public function giveUserList(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        //工艺选择
        $give_status = GiveModel::$give_status_search;
        unset($give_status[0]);

        $status = input('status');
        // 获取查询条件
        $map = $this->getMap();
        if(!empty($status))$map[] = ['l.status','=',$status];
        $data_list = [];
        if(!empty($map)){
            $map[] = ['l.is_bu','=',0];
            $data_list = Db::name('mill_order_archives_give_log')
                ->alias('l')
                ->field('l.status_uid,count(l.id) as number_sum,sum(l.one_area) as area_sum')
                ->where($map)
                ->group('l.status_uid')
                ->order('number_sum desc')
                ->paginate()
                ->each(function ($v){

                    $user = Db::name('mill_staff')->where(['id'=>$v['status_uid']])->find();
                    $v = array_merge($v,$user);
                    $v['nickname'] = "{$v['staff']}";

                    return $v;
                })
            ;
        }

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('工艺列表') // 页面标题
            ->setTableName('mill_order_archives_give_log') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['select:2', 'l.status_uid', '操作员','','',ClientModel::getStaffList(3)],
                ['select:2', 'l.mill_id', '车间','','',ClientModel::getMillList()],
                ['select:2', 'l.status', '工艺环节','','',$give_status],
                ['daterange:2', 'l.status_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['nickname', '操作人员','','','','badge-green',['group'=>'工艺环节产量数据']],
                ['number_sum', '数量(件)','','','','',['group'=>'工艺环节产量数据']],
                ['area_sum', '面积(㎡)','','','','',['group'=>'工艺环节产量数据']],
                ['right_button', '操作', 'btn','','','',['group'=>'操作']],
            ])
            ->addTopButton('print',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print','float'=>'right','lay-event'=>'quality-print'])
            ->addRightButton('speedIndex',['title' => '扫码明细','href' => url('mill/give/speedIndex',['uid' => '__id__']),'class'=>'btn btn-default'],false)
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    //操作员列表
    public function giveUserList2(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        //工艺选择
        $give_status = GiveModel::$give_status_search;
        unset($give_status[0]);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['is_bu','=',0];
        $data_list = Db::name('mill_order_archives_give_log')
            ->alias('l')
            ->field('status_uid,count(l.id) as number_sum,sum(l.one_area) as area_sum')
            ->where($map)
            ->group('l.status_uid')
            ->order('number_sum desc')
            ->paginate()
            ->each(function ($v){

                $user = Db::name('mill_staff')->where(['id'=>$v['status_uid']])->find();
                $v = array_merge($v,$user);
                $v['nickname'] = "{$v['staff']}";

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('操作员') // 页面标题
            ->setTableName('mill_order_archives_give_log') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['select:2', 'l.mill_id', '车间','','',ClientModel::getMillList()],
                ['select:2', 'l.status', '工艺环节','','',$give_status],
            ])
            ->addColumns([ // 批量添加列
                ['nickname', '操作人员','jump_right','','status_uid=__id__','badge-green',['group'=>'工艺环节产量数据']],
                ['number_sum', '数量(件)','','','','',['group'=>'工艺环节产量数据']],
                ['area_sum', '面积(㎡)','','','','',['group'=>'工艺环节产量数据']],
            ])
            ->addTopButton('print',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print','float'=>'right','lay-event'=>'quality-print'])
            ->setRowList($data_list) // 设置表格数据
            ->setWidth('20%') // 设置表格宽度
            ->setColumnWidth([
                'id'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    //产品生产进度列表页首页
    public function speedIndex(){

        $uid = input('uid');
        if (strpos($uid, ',') !== false)$this->error('暂不支持批量查看');
        session('_speed_uid',$uid);

        $top_html = $this->giveIndexHtml(url('mill/stat/ajaxMonthGive'));

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('') // 页面标题
            ->setTableName('mill_order_archives') // 设置表名
            ->setExtraHtml($top_html,'block_top')
            ->fetch(); // 渲染模板
    }
    //产品生产进度列表页
    public function speed()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $status_uid = input('status_uid',session('_speed_uid'));
        $is_table = false;
        $_listRows = input('list_rows',GiveModel::$_listRows);
        // 获取查询条件
        $map = $this->getMap();
        if(empty($map) && $status_uid)$map[] = ['g.status_uid','=',$status_uid];
        if(!empty($map)){
            foreach ($map as $m_v_i=>$m_v){
                if($m_v[0] == 'g.status_uid' || $m_v[0] == 'g.status') $is_table = true;
            }
        }
        if($is_table) $map[] = ['is_bu','=',0];
        $map = array_merge($map);

        //工艺选择
        $give_status = GiveModel::$give_status_search;
        unset($give_status[0]);
        //扫码人
        $user_list = ClientModel::getStaffList(3);
        $data_list = [];
        if(!empty($map)){

            $table = 'mill_order_archives_give';
            if($is_table) $table = 'mill_order_archives_give_log';

            // 数据列表
            $data_list = Db::name($table)
                ->alias('g')
                ->field("g.*,o.engineering,o.batch as o_batch,a.one_area,a.model,a.model_sn,a.thickness,a.color,a.sort as a_sort")
                ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                ->leftJoin('mill_order o','o.id=g.order_id')
                ->where($map)
                ->order('g.status_time desc')
                ->paginate($_listRows);

            if(!empty($data_list)){
                foreach ($data_list as $k=>$v){

                    //序号
                    $v['a_sort'] = "{$v['a_sort']}-{$v['counter']}";
                    //二维码
                    $v['give_sn_code'] = '<div class="js-gallery"><img class="layui-img" style="width: 20px" src="'.plugin_url('Qrcode/Qrcode/generate', ['text' => $v['give_sn']]).'" /></div>';
                    //扫码人
                    $v['nickname'] = isset($user_list[$v['status_uid']])?$user_list[$v['status_uid']]:'已禁用';
                    //生产状态
                    $v['status_str'] = '<span class="label label-primary">'.GiveModel::$give_status[$v['status']];
                    if($v['quality_status']<0)$v['status_str'] .= GiveModel::$quality_status[$v['quality_status']];
                    elseif ($v['quality_status'] == -3)$v['status_str'] = '<span class="label label-primary">'.GiveModel::$quality_status[$v['quality_status']];
                    $v['status_str'] .= '</span>';

                    $data_list[$k] = $v;

                }
            }

        }

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('扫码明细') // 页面标题
            ->setTableName('mill_order_archives_give') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['select:1', 'g.status', '工艺环节','','',$give_status],
                ['select:3', 'g.order_id', '档案号/工程名称','','',OrderModel::getList("concat(archives_sn,' ',engineering) as str_name")],
                ['text:2', 'g.give_sn', '条码编号', 'like'],
                ['select:2', 'g.status_uid', '扫码人', 'like', '', $user_list],
                ['daterange:2', 'g.status_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['archives_sn', '档案号','','','','badge-green',['group'=>'产品信息']],
                ['engineering', '工程名称','','','','',['group'=>'产品信息']],
                ['o_batch', '批次','','','','',['group'=>'产品信息']],
                ['color', '颜色','','','','',['group'=>'产品信息']],
                ['model', '版型','','','','',['group'=>'产品信息']],
                ['a_sort','序号','','','','',['group'=>'产品信息']],
                ['one_area', '面积M²','','','','',['group'=>'产品信息']],
                ['give_sn', '二维码编码','','','','',['group'=>'产品信息']],
                ['give_sn_code', '二维码','','','','',['group'=>'产品信息']],
                ['model_sn', '铝板编号','','','','',['group'=>'产品信息']],
                ['status_str','生产状态','','','','',['group'=>'产品信息']],
                ['status_time','扫码时间','date','','','',['group'=>'产品信息']],
                ['nickname','扫码人','','','','',['group'=>'产品信息']],
            ])
            ->addTopButton('print',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print','float'=>'right','lay-event'=>'quality-print'])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'thickness'  => 50,
                'number'  => 30,
                'one_area'  => 70,
                'a_sort'  => 60,
                'give_sn'  => 110,
                'status_time'  => 80,
                'status'  => 60,
                'o_batch'  => 60,
                'give_sn_code'  => 40,
                'engineering'  => 150,
            ])
            ->fetch(); // 渲染模板
    }
    //质检管理列表页
    public function quality(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        //扫码人
        $user_list = ClientModel::getUserList('all');

        // 获取查询条件
        $map = $this->getMap();
        // 数据列表
        $data_list = Db::name('mill_order_archives_give_quality')
            ->alias('g')
            ->field('g.*,o.engineering,o.batch as o_batch,a.one_area,a.model,a.model_sn,a.thickness,a.color,a.sort as a_sort')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->where($map)
            ->order('g.quality_time desc')
            ->paginate();

        if(!empty($data_list)){
            foreach ($data_list as $k=>$v){

                //序号
                $v['a_sort'] = "{$v['a_sort']}-{$v['counter']}";
                //二维码
                $v['give_sn_code'] = '<div class="js-gallery"><img class="layui-img" style="width: 20px" src="'.plugin_url('Qrcode/Qrcode/generate', ['text' => $v['give_sn']]).'" /></div>';
                //扫码人
                $v['nickname'] = isset($user_list[$v['status_uid']])?$user_list[$v['status_uid']]:'账号不存在';
                //扫码人
                $v['quality_uid'] = isset($user_list[$v['quality_uid']])?$user_list[$v['quality_uid']]:'账号不存在';
                //生产状态
                $v['status_str'] = '<font class="text-danger">'.GiveModel::$give_status[$v['status']].'</font>';

                $data_list[$k] = $v;

            }
        }

        //部门列表
        //$group_list = UserGroupModel::where([['id','in',implode(',',array_values(GiveModel::$quality_group))]])->column('id,name');

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('质量事故列表（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_order_archives_give_quality') // 设置表名
            ->setExtraHtml($this->giveIndexHtml(url('mill/stat/ajaxQuality')),'block_top')
            ->setSearchArea([
                ['select:1', 'g.quality_status', '状态','','', GiveModel::$quality_status],
                ['select:3', 'g.order_id', '档案号/工程名称','','',OrderModel::getList("concat(archives_sn,' ',engineering) as str_name")],
                ['text:2', 'a.sort', '序号', 'like'],
                ['text:2', 'g.give_sn', '二维码', 'like'],
                //['select:2', 'g.quality_flow_group', '责任部门','','', $group_list],
                ['daterange:2', 'g.quality_time', '质检日期'],
            ])
            ->addColumns([ // 批量添加列
                ['archives_sn', '档案号','','','','badge-green',['group'=>'产品信息']],
                ['engineering', '工程名称','','','','',['group'=>'产品信息']],
                ['o_batch', '批次','','','','',['group'=>'产品信息']],
                ['color','颜色','','','','',['group'=>'产品信息']],
                ['model', '版型','','','','',['group'=>'产品信息']],
                ['a_sort','序号','','','','',['group'=>'产品信息']],
                ['one_area', '面积M²','','','','',['group'=>'产品信息']],
                ['give_sn', '二维码编码','','','','',['group'=>'产品信息']],
                ['give_sn_code', '二维码','','','','',['group'=>'产品信息']],
                ['model_sn', '铝板编号','','','','',['group'=>'产品信息']],
                ['nickname','生产员工','','','','',['group'=>'生产信息']],
                ['status_time','生产时间','date','','','',['group'=>'生产信息']],
                ['status_str','事故环节','','','','',['group'=>'质量检查明细']],
                ['quality_errors','错误原因','','','','',['group'=>'质量检查明细']],
                ['quality_uid','质检人','','','','',['group'=>'质量检查明细']],
                ['quality_time','质检时间','date','','','',['group'=>'质量检查明细']],
                ['quality_note','备注','','','','',['group'=>'质量检查明细']],

            ])
            ->addTopButton('qualityErrors',['title' => '设置质检错误原因','href' => url('qualityErrors'),'icon'=>'','class'=>'btn btn-default','float'=>'left'])
            ->addTopButton('ablequality',['title' => '批量质检','href' => url('ablequality'),'icon'=>'','class'=>'btn btn-primary dch-js-get','float'=>'right'])
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn btn-default quality-print','float'=>'right'])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'give_sn'  => 120,
                'quality_note'  => 150,
                'engineering'  => 110,
                'batch'  => 60,
                'a_sort'  => 40,
                'slot'  => 40,
                'weld'  => 40,
                'long'  => 60,
                'high'  => 60,
                'one_area'  => 60,
                'thickness'  => 40,
                'quality_flow_group'  => 70,
                'quality_status'  => 60,
                'quality_time'  => 90,
                'archives_sn'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    //质检管理 报废or修复
    public function ablequality()
    {
        $user = session('user_auth');
        $data = input();
        $ids = is_array($data['ids'])?implode(',',$data['ids']):$data['ids'];
        if(empty($ids))$this->error('请选择产品');

        $where[] = ['id','in',$ids];
        $give_sn = Db::name('mill_order_archives_give_quality')->where($where)->column('give_sn','id');
        $give_sn = implode(",",array_values($give_sn));
        if(empty($data['give_sn']))$data['give_sn'] = $give_sn;

        if ($this->request->isPost()){

            //关闭子窗口，并刷新父窗口
            if (GiveModel::quality($user,$data,false)) $this->success('操作成功','','_parent_reload');

            $this->error('操作失败');
        }

        $info['give_sn'] = $give_sn;
        $info['status'] = '-1';
        $quality_status = GiveModel::$quality_status;
        $give_status_search = GiveModel::$give_status_search;
        unset($quality_status['-3']);
        unset($quality_status[0]);
        unset($give_status_search[0]);
        return ZBuilder::make('form')
            ->setPageTitle('质检') // 页面标题
            ->addHidden('give_sn')
            ->addStatic('give_sn', '产品编号', '', $give_sn)
            ->addFormItems([ // 批量添加表单项
                //['text:||||must', 'address_sn','发货单号', $address_sn],
                ['radio:12||||must', 'status', '质检状态','',$quality_status],
                ['radio:12||||must', 'give_status', '修复环节','',$give_status_search],
                ['text:12||||must', 'quality_note', '备注'],
            ])
            ->setFormData($info)
            ->submitConfirm()
            ->layout(['give_sn'=>12])
            ->fetch();

    }
    //质检管理列表页
    public function qualityErrors(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $config = new ConfigModel();

        if ($this->request->isPost()){

            $mill_quality_errors = input('mill_quality_errors');
            //更新错误原因
            ConfigModel::where('name', 'mill_quality_errors')->update(['value' => $mill_quality_errors]);
            //关闭子窗口，并刷新父窗口
            $this->success('操作成功','','_parent_reload');

            $this->error('操作失败');
        }

        $mill_quality_errors = $config->getConfig('mill_quality_errors');

        return ZBuilder::make('form')
            ->setPageTitle('设置质检错误原因') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['textarea:12||||must', 'mill_quality_errors', '错误原因','',$mill_quality_errors],
            ])
            ->fetch();
    }

}
